#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:洪卫
 

import os,sys
import serial
import time
import json
import timetool
from sys import version_info  

def pythonVersion():
    return version_info.major

class TimeObj(object):
    """docstring for TimeObj"""
    def __init__(self):
        super(TimeObj, self).__init__()
        self.timedict = {}
        self.times = []
        self.initTimer()
    def initTimer(self):
        f = open('timer.json','r')
        dat = f.read()
        configs = json.loads(dat)
        f.close()
        for i,v in enumerate(configs):
            tmptime = int(timetool.conventTimeFromStrConfig(v['time'])*1000)
            self.timedict[tmptime] = v['number']
            self.times.append(tmptime)
        self.times.sort()

serialT = None

def readPort():
    global serialT
    time.sleep(0.003)
    n = serialT.inWaiting()
    # print(n)
    if n > 0:
        pstr = serialT.read(n)
        if pythonVersion() == 2:
            # return pstr
            print('setial read:%s'%(pstr))
        else:
            # return str(pstr)
            print('setial read:%s'%(str(pstr)))


def sendCmd(pcmd):
    global serialT
    back = None
    if pythonVersion() > 2:
        back = serialT.write(pcmd.encode())
    else:
        back = serialT.write(pcmd)
    serialT.flush()
    print('send cmd,:%s,isOk:%s'%(pcmd,str(back)))
    return back


def main():
    global serialT
    f = open('config.json','r')
    jstr = f.read()
    f.close()
    jdic = json.loads(jstr)
    t = serial.Serial(jdic['port'],jdic['btv'],timeout=0.5)
    serialT = t
    time.sleep(2)
    sendCmd('t')
    readPort()
    taskobj = TimeObj()
    times = taskobj.times
    while True:
        time.sleep(0.005)
        nowtime = int(time.time()*1000)
        if len(times) > 0 and times[0] <= nowtime:
            if nowtime - times[0] > 60: #一分钟前已点击，这里直接认为时间为无效
                ptime = times.pop(0)
                taskobj.timedict.pop(ptime)
                print('time is passed:%s'%(timetool.getNowDate(ptime/1000)))
            else:
                touchdat = taskobj.timedict.pop(times.pop(0))
                key = touchdat['key']
                tmpcount = touchdat['times']
                delay = touchdat['delay']
                while tmpcount > 0:
                    sendCmd(key)
                    readPort()
                    if delay > 0:
                        time.sleep(delay/1000.0)
                    else:
                        time.sleep(0.005)
                    tmpcount -= 1
        elif len(times) < 1:
            taskobj.initTimer()
            times = taskobj.times
            time.sleep(1.0)
            print('init times again')
    
if __name__ == '__main__':
    main()